const koa = require('koa')
const app = new koa()
var mysql = require('mysql');
const bodyParser = require('koa-bodyparser')
const path = require('path')
const uploader = require('./middleware/uploadFile')
var connection = mysql.createConnection({
    host: 'localhost', // 主机
    user: 'root', // 
    password: '123456',
    database: 'juejin'
});
// connection.connect();
const koaRouter = require('koa-router');
const router = koaRouter()
app.use(uploader)
app.use(bodyParser())
app.use(router.routes())
app.use(router.allowedMethods())

app.use(async (ctx, next) => {
    console.log('第一个中间件开始')
    await next() // 去执行下一个中间件，当第二个中间件全部执行结束，才会回来继续执行
    console.log('第一个中间件结束')
})
app.use(async (ctx, next) => {
    console.log('第二个中间件开始')
    await next()
    console.log('第二个中间件结束')
})

// 获取所有博客
router.get('/blogs', async (ctx, next) => {
    try {
        // 获取所有的博客
        const res = await new Promise((resolve, reject) => {
            connection.query('select * from blog', (err, results) => {
                if (err) reject(err)
                resolve(results)
            })
        })
        ctx.body = {
            code: 1,
            data: res
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            msg: e
        }
    }

})

router.get('/blogs/author', async (ctx, next) => {
    try {
        const {
            author
        } = ctx.request.query
        const res = await new Promise((resolve, reject) => {
            connection.query(`select * from blog where author="${author}"`, (err, results) => {
                if (err) reject(err)
                resolve(results)
            })
        })
        ctx.body = {
            code: 1,
            data: res
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            error: e
        }
    }

})
router.post('/login', async (ctx, next) => {
    console.log(ctx.request.body)
    ctx.body = {
        code: 1,
        msg: '登陆成功'
    }
})
router.post('/register', async(ctx, next) => {
    try {
        // 注册的接口：使用手机号、密码进行注册，手机号唯一
        const { phone, password } = ctx.request.body
        // 查看手机号是否已被注册
        const userRes = await new Promise((resolve, reject) =>{
            connection.query('select * from users where phone=?', phone, (err, results)=>{
                if(err) reject(err)
                resolve(results)
            })
        })
        if(userRes.length === 0) {
            // 手机号未被使用，可以进行注册
            await new Promise((resolve, reject) => {
                connection.query('insert into users set ?', {phone, password}, (err, results) => {
                    if(err) reject(err)
                    console.log(results)
                    resolve(results)
                })
            })
            ctx.body = {
                code: 1,
                msg: '恭喜，注册成功，请登录'
            }
        } else {
            ctx.body = {
                code: 0,
                msg: '该手机号已被占用，请输入正确的手机号'
            }
        }
    } catch (error) {
        ctx.body = {
            code: 0,
            msg: 1
        }
    }
})
router.post('/users/update', async(ctx, next) => {
    try {
        // 修改用户信息接口
        const { phone, name } = ctx.request.body
        // 修改数据
        await new Promise((resolve, reject) => {
            connection.query('update users set name=? where phone=?', [name, phone], (err, results) => {
                if(err) reject(err)
                resolve()
            })
        })
        ctx.body = {
            code: 1,
            msg: '修改成功'
        }
    } catch (error) {
        ctx.body = {
            code: 0,
            msg:error
        }
    }
})

router.post('/users/del', async(ctx, next) => {
    try {
        // 删除某一个用户
        const { phone } = ctx.request.body
        await new Promise((resolve, reject) => {
            connection.query('delete from users where phone=?', [phone], (err, results) =>{
                if(err) reject(err)
                resolve()
            })
        })
        ctx.body = {
            code: 1,
            msg: '删除成功'
        }
    } catch (error) {
        ctx.myError = error
        await next()
    }
})
router.get('/users/dim', async(ctx, next) => {
    try {
        // 模糊搜索
        const { name } = ctx.request.query
        // 去数据库里面查找
        const res = await new Promise((resolve, reject) => {
            connection.query('select from users where name like ?', `%${name}%`, (err, results) => {
                if(err) reject(err)
                resolve(results)
            })
        })
        ctx.body = {
            code: 1,
            data: res
        }
    } catch (error) {
        ctx.myError = error
        await next()
    }
})
// 文件上传:音乐、表格、txt、图片等等等等
router.post('/upload', async(ctx, next) => {
    console.log(ctx.bufData)
})
app.use(async(ctx, next) => {
    ctx.body = {
        code: 0,
        msg: ctx.myError
    }
})
app.listen(3000, _ => {
    console.log('服务器已启动在3000端口')
})